<?php
namespace Home\Controller;
use Think\Controller;

class FlowController extends Controller{
	//把商品添加到购物车
       public function add(){
       	//根据地址栏的goods_id,查询商品信息
           $goods = D('goods');
           if(!$goods->find(I('get.goods_id'))){
           	$this->redirect('/');
           }



           //实例化购物车类，获取商品信息
           $cart = \Home\Tool\CartTool::getIns();


           //把商品信息添加到购物车
          $cart ->add($goods->goods_id , $goods->goods_name , $goods->shop_price);

          //把商品信息checkout页面
          $this->redirect('Home/Flow/checkout');


       }

       //购物车展示页面，准备下单
       public function checkout(){
           //实例化购物车类
          $cart =\Home\Tool\CartTool::getIns();

          $this->assign('goods',$cart->items());

          $this->assign('money',$cart->calcMoney());


          $this->display();

       }


   //正式下单
       public function done(){

       	$cart = \Home\Tool\CartTool::getIns();
          $order =  D('ordinfo');
          $order->create();

          $order->ord_sn  = $ord_sn= date('Ymd').rand(1000,9999);

          $order->user_id = cookie('user_id') ? cookie('user_id') :0;

          $order->money = $money = $cart ->calcMoney();

          $order->ordtime = time();

          //$order->add()? 'ok':'fail';
          if($order_id = $order->add()){
            //添加到ordgoods表

            $ord = D('ordgoods');
            
             //批量插入数据
           $data = array();
            
            foreach($cart->items() as $k =>$v){
            $row = array();
            $row['goods_id'] = $k;
            $row['goods_name'] = $v['goods_name'];
            $row['shop_price'] = $v['shop_price'];
            $row['goods_num'] = $v['num'];
            $row['ordinfo_id'] = $order_id;


            $data[] = $row;
            }
            
          if($ord ->addAll($data)){
               $this->assign('ord_sn' , $ord_sn);
               $this->assign('money' , $money);


               //在线支付
              // $jdpay = new \Home\Pay\JdPay($ord_sn , $money);
               //$this -> assign('form' , $jdpay-> form());

               // 在线支付
                $jdpay = new \Home\Pay\JdPay($ord_sn , $money);
                $this->assign('form' , $jdpay->form());

               $cart->clear();
               $this->display();
             }
          }else{
            echo 'error';
          }


       	
       }



}